<?php

/**
 * descript:
 * User: blue
 * Date: 2018/9/13 16:47
 */

namespace app\library\base;

use app\library\except\ParmasException;
use think\Db;
use think\Exception;
use think\Model;
// use think\model\concern\SoftDelete;

class BaseModel extends Model{
/*  需要引入软删除trait时手动引入
    use SoftDelete;
    protected $deleteTime = 'delete_time';*/

    //baseModel自定义属性
    protected $updateFields=true;
    protected $insertFields=true;

    //------------------模型验证钩子函数------------------
    protected function before_insert($data){}
    protected function after_insert($data){}
    protected function before_update($data){}
    protected function after_update($data){}
    protected function before_delete($data){}
    protected function after_delete($data){}


    //----------------------通用curd操作----------------------
    /**
     * 通用添加
     * @param $data
     */
    public function add($data){
        //注册钩子函数
        method_exists(__CLASS__,'before_insert')&&$this->before_insert($data);
        $res=$this->allowField($this->insertFields)->save($data);
        if(!$res) throw new Exception();
        method_exists(__CLASS__,'after_insert')&&$this->after_insert($data);
        return $res;
    }

    /**通用更新
     * @param $data
     */
    public function edit($data){
        method_exists(__CLASS__,'before_update')&&$this->before_update($data);
        if(!isset($data['id']) || empty($data)){
            throw new ParmasException('请传入修改的规则id');
        }
        $res=$this->allowField($this->updateFields)->save($data,['id' => $data['id']]);
        if(!$res) throw new Exception('数据更新失败');
        method_exists(__CLASS__,'after_update')&&$this->after_update($data);
        return $res;
    }

    /**通用自定义软删除
     * @param $id
     * @return bool|void
     */
    public function del($ids){
        if($ids==="") throw new ParmasException('删除必须指定id');
        //添加事务处理
        Db::startTrans();
        try{
            method_exists(__CLASS__,'before_delete')&&$this->before_delete($ids);
            $res=self::destroy($ids);
            method_exists(__CLASS__,'after_delete')&&$this->after_delete($ids);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        return $res;
    }

    /**
     * @param $page
     * @param $limit
     *
     */
    public function lists($page,$limit,$keyword=''){
        //获取默认分页配置
        $listRow=$limit?$limit:config('api.list_page_size');
        //拼接sql条件
        $map=[];
        /*limit 方式分页
        Db::table('think_article')->limit(10,25)->select();*/
        /*page方式分页*/
        $data=$this->where($map)->page($page,$listRow)->select();
        return $data;
    }
}